//
//  ModifyPwdController.swift
//  chat
//
//  Created by 崔世强 on 2018/11/9.
//  Copyright © 2018 崔世强. All rights reserved.
//

import UIKit
import Toast_Swift

class ModifyPwdController: UITableViewController {

    @IBOutlet weak var oldPwdField: UITextField!
    
    @IBOutlet weak var newPwdField: UITextField!
    
    @IBOutlet weak var newPwdConfirmField: UITextField!
    
    @IBOutlet weak var doneBtn: UIBarButtonItem!
    
    @IBAction func doneBtnClick(_ sender: UIBarButtonItem) {
        let oldPwd = self.oldPwdField.text!
        let newPwd = self.newPwdField.text!
        let newPwdConfirm = self.newPwdConfirmField.text!
        
        if !newPwdValid(pwd:newPwd,confirm:newPwdConfirm) {
            self.view.makeToast("两次新密码输入不一致",position:.center)
            return
        }
        
        if !isPassword(newPwd) {
            self.view.makeToast("密码必须8~16个字符，而且同时包含字母和数字,",position:.center)
            return
        }
        
        self.view.makeModalToastActivity(.center)
        let userId = AppStatusManager.instance.userLoginStatus.1 ?? 0
        IM.request(.modifyPwd(userId:userId,oldPwd:oldPwd,newPwd:newPwd), success: { (json) in
            if reqSuccess(json["code"].stringValue) { //如果操作成功
                DispatchQueue.main.async {
                    self.view.hideModalToastActivity()
                    self.navigationController?.popViewController(animated: true)
                }
            } else {
                DispatchQueue.main.async {
                    self.view.hideModalToastActivity()
                    self.view.makeToast(json["msg"].stringValue, duration: 3.0, position: .center)
                }
            }
        }, error: { (code) in
            print("请求错误！错误码：\(code)")
            DispatchQueue.main.async {
                self.view.hideModalToastActivity()
                self.view.makeToast("修改密码失败", duration: 3.0, position: .center)
            }
        }) { (error) in
            print("请求失败！错误信息：\(error.errorDescription ?? "")")
            DispatchQueue.main.async {
                self.view.hideModalToastActivity()
                self.view.makeToast("网络有问题，请稍后再试", duration: 3.0, position: .center)
            }
        }
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.oldPwdField.addTarget(self, action: #selector(valueDidChange(_:)), for: .editingChanged)
        self.newPwdField.addTarget(self, action: #selector(valueDidChange(_:)), for: .editingChanged)
        self.newPwdConfirmField.addTarget(self, action: #selector(valueDidChange(_:)), for: .editingChanged)
    }
    
    func isPassword(_ pasword : String) -> Bool {
        let pwd =  "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$"
        let regextestpwd = NSPredicate(format: "SELF MATCHES %@",pwd)
        return regextestpwd.evaluate(with: pasword)
    }
    
    func newPwdValid(pwd:String,confirm:String) -> Bool {
        return pwd == confirm
    }
}

extension ModifyPwdController {
    
    @objc func valueDidChange(_ sender:UITextField) {
        let oldPwdFieldEmpty = self.oldPwdField.text?.isEmpty ?? true
        let newPwdFieldEmpty = self.newPwdField.text?.isEmpty ?? true
        let newPwdConfirmEmpty = self.newPwdConfirmField.text?.isEmpty ?? true
        self.doneBtn.isEnabled = !oldPwdFieldEmpty && !newPwdFieldEmpty && !newPwdConfirmEmpty
    }
    
    
}
